import Icon, { DownOutlined, PlusSquareOutlined } from '@ant-design/icons';
import { Tree } from 'antd';
import React, { useState } from 'react';
import styles from './index.less';

const { TreeNode } = Tree;
/**
 * @description: 受控树
 * @param [{}]
 * @return: React Node
 */
const TreeControlled = (props: any) => {
  const {
    data = [],
    checkable = false,
    selectable = false,
    checkedKeys,
    showLine,
    setCheckedKeys,
    expandedKeys,
    setExpandedKeys,
    selectedKeys,
    setSelectedKeys,
    setHalfCheckedKeys,
    renderTreeNodes,
    renderTitle = ({ title }: any) => title,
    className,
    autoExpandParent: autoExpandParentProp = true,
    title,
    ...rest
  } = props;
  const filterData = data && data instanceof Array ? data : [];
  const _renderTreeNodes = (data: any[]) =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={renderTitle(item)} key={item.key} icon={item.icon || null} {...item} dataRef={item}>
            {_renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} icon={item.icon || null} title={renderTitle(item)} />;
    });

  const [_checkedKeys, _setCheckedKeys] = useState([]);
  const [_expandedKeys, _setExpandedKeys] = useState([]);
  const [_selectedKeys, _setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(autoExpandParentProp);

  const _onExpand = (keys: React.SetStateAction<never[]>) => {
    setAutoExpandParent(false);
    if (setExpandedKeys) {
      setExpandedKeys(keys);
    } else {
      _setExpandedKeys(keys);
    }
  };

  const _onCheck = (keys: React.SetStateAction<never[]>, { halfCheckedKeys }: any) => {
    setAutoExpandParent(false);
    if (setCheckedKeys) {
      setCheckedKeys(keys);
    } else {
      _setCheckedKeys(keys);
    }
    if (setHalfCheckedKeys) {
      setHalfCheckedKeys(halfCheckedKeys);
    }
  };

  return (
    <div className={className}>
      {title && <p className={`treeTitle ${styles.defaultTitle}`}>{title}</p>}
      <Tree
        showLine
        showIcon={!showLine}
        checkable={checkable}
        selectable={selectable}
        autoExpandParent={autoExpandParent}
        checkedKeys={checkedKeys || _checkedKeys}
        onCheck={_onCheck}
        onExpand={_onExpand}
        expandedKeys={expandedKeys || _expandedKeys}
        selectedKeys={selectedKeys || _selectedKeys}
        onSelect={setSelectedKeys || _setSelectedKeys}
        {...rest}
      >
        {renderTreeNodes ? renderTreeNodes(filterData) : _renderTreeNodes(filterData)}
      </Tree>
    </div>
  );
};

export default TreeControlled;
